Middleware in Next.js

Middleware runs before a request reaches a route. It allows you to control, redirect, or block requests globally.

Definition

Middleware is a special function that executes before a page or API route loads. It intercepts incoming requests and decides whether to allow, modify, or redirect them.

Why We Use Middleware

When To Use Middleware

Use Middleware when logic must run before every request or before specific routes load, such as checking login status or redirecting users.

How It Works

Request Flow:

User → Middleware → Route/Page

Middleware runs first. Based on conditions, it either:

Example Code

import { NextResponse } from "next/server";

export function middleware(request) {
  const isLoggedIn = false;

  if (!isLoggedIn) {
    return NextResponse.redirect(new URL("/login", request.url));
  }

  return NextResponse.next();
}

If the user is not logged in, they are redirected to the login page.

Real-World Example

In an admin dashboard, Middleware checks if a user has admin access before allowing entry to /admin. If not, the user is redirected to /login or /unauthorized.

Interview Tip

Middleware in Next.js runs before a request reaches a route and is commonly used for authentication, redirects, and global request handling.